﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Net;
using System.IO;
using System.Xml;
using QueueLoad.controls;

namespace AppDemo
{
    /// <summary>
    /// Interaction logic for Window9.xaml
    /// </summary>
    public partial class Window9 : Window
    {
        XmlDataProvider ds;
        WebClient _wc = new WebClient();
        public Window9()
        {
            InitializeComponent();
            //http://cn.bing.com/images?q=wpf&format=xml&first=1
            ds = new XmlDataProvider();

            ds.XPath = "searchresult/documentset";
            var binding = new Binding() { Source = ds, XPath = "document" };
            cc.SetBinding(ItemsControl.ItemsSourceProperty, binding);

            _wc.OpenReadCompleted += _wc_OpenReadCompleted;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string callbackXml = CallUrlRequest(string.Format
                ("http://cn.bing.com/images?q={0}+filterui:imagesize-small&format=xml&first=1", aaaa.Text));
            XmlDocument doc = new XmlDocument();
            doc.InnerXml = callbackXml;
            doc.Save("images.xml");
            ds.Source = null;
            ds.Source = new Uri(@"D:\develop\wpf\XWord2\trunk\Common\AppDemo\bin\Debug\images.xml");

        }

        public static string CallUrlRequest(string url)
        {
            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse response = (HttpWebResponse)myReq.GetResponse();
            Stream dataStream = response.GetResponseStream();

            StreamReader reader = new StreamReader(dataStream, UTF8Encoding.UTF8);

            string responseFromServer = reader.ReadToEnd();
            response.Close();
            reader.Close();
            dataStream.Close();
            return responseFromServer;
        }


        void _wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                BitmapImage _bitMap = new BitmapImage();
                // _bitMap.StreamSource=e.Result;
                _bitMap.BeginInit();

                _bitMap.StreamSource = e.Result;
                _bitMap.EndInit();
                ImageItemBase _itemBase = e.UserState as ImageItemBase;
                _itemBase.img.Height = 200;
                _itemBase.img.Width = 200;
                _itemBase.img.Source = _bitMap;
                _itemBase.img.Visibility = Visibility.Visible;
                _itemBase.loading.Visibility = Visibility.Collapsed;

                 LoadImage();//关键，继续加载下一个(是不是有点ajax中http长连接的意思，呵)

            }
        }

        private void ImageItemBase_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            var _itemBase = sender as ImageItemBase;
            var doc = e.NewValue as XmlNode;
            foreach (XmlNode item in doc.ChildNodes)
            {
                if (item.Name == "mediaurl")
                {
                    _mageItemBaseStack.Enqueue(_itemBase);
                    _imgStack.Enqueue(item.InnerText);
                    LoadImage();
                }
            } 
        }

        void LoadImage()
        {
            if (_imgStack != null && _imgStack.Count > 0 && !_wc.IsBusy)
            {
                var _itemBase = _mageItemBaseStack.Dequeue();
                _itemBase.loading.Visibility = Visibility.Visible;
                _itemBase.img.Visibility = Visibility.Collapsed;
                Uri _imgUri = new Uri(_imgStack.Dequeue());
                _wc.OpenReadAsync(_imgUri, _itemBase);
            }
        }

        Queue<ImageItemBase> _mageItemBaseStack = new Queue<ImageItemBase>();
        Queue<string> _imgStack = new Queue<string>();//如要倒序加载，换成 Queue<string>

    }
}
